import Footer from '@/components/Footer';
import {
  LockOutlined, UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm, ProFormText,
} from '@ant-design/pro-components';
import { history} from '@umijs/max';
import {Divider, message, Space, Tabs} from 'antd';
import React, { useState } from 'react';
import {SYSTEM_LOGO} from "@/constants";
import {FormattedMessage, Helmet, Link, SelectLang, useIntl} from "@@/exports";
import {useEmotionCss} from "@ant-design/use-emotion-css";
import {passwordBackUsingPOST} from "@/services/cmapi-backend/userController";
import Settings from "../../../../config/defaultSettings";

const Lang = () => {
  const langClassName = useEmotionCss(({ token }) => {
    return {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  return (
    <div className={langClassName} data-lang>
      {SelectLang && <SelectLang />}
    </div>
  );
};


const Update: React.FC = () => {
  const [type, setType] = useState<string>('update');

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });
  const intl = useIntl();

  const handleSubmit = async (values: API.UserPasswBackRequest) => {
    try {
      // 密码找回
      const res = await passwordBackUsingPOST({ ...values });
      if (res.data) {
        // 密码找回成功后，返回登录页
        history.push('/user/login',);
        message.success('密码找回成功，请登录！');
        return;
      }
    } catch (error) {
      const defaultUpdateFailureMessage = intl.formatMessage({
        id: 'pages.update.failure',
        defaultMessage: '密码找回失败，请重试！',
      });
      console.log(error);
      message.error(defaultUpdateFailureMessage);
    }
  };

  return (
    <div className={containerClassName}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.update',
            defaultMessage: '用户密码找回页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang />
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          submitter={{
            searchConfig: {
              submitText: '用户密码找回'
            }
          }}
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src={SYSTEM_LOGO} />}
          title="沉梦接口开放平台"
          subTitle={'一个免费的 API 调用平台'}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.UserPasswBackRequest);
          }}
        >
          <Tabs
            activeKey={type}
            onChange={setType}
            centered
            items={[
              {
                key: 'update',
                label: intl.formatMessage({
                  id: 'pages.update.tab',
                  defaultMessage: '用户密码找回',
                }),
              },
            ]}
          />
          {type === 'update' && (
            <>
              <ProFormText
                name="userAccount"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.update.username.placeholder',
                  defaultMessage: '请输入要找回的账号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.update.username.required"
                        defaultMessage="账号是必填项!"
                      />
                    ),
                  },
                  {
                    min: 4,
                    type: 'string',
                    message: '账号长度不能小于 4',
                  },
                ]}
              />
              <ProFormText
                name="email"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.update.email.placeholder',
                  defaultMessage: '邮箱',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.update.email.required"
                        defaultMessage="邮箱是必填项!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="newPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.pages.update.placeholder',
                  defaultMessage: '输入新密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.pages.update.required"
                        defaultMessage="请输入密码"
                      />
                    ),
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '密码长度不能小于 8',
                  },
                ]}
              />
              <ProFormText.Password
                name="checkPassword"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.pages.update.placeholder',
                  defaultMessage: '确认密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.pages.update.required"
                        defaultMessage="确认密码是必填项！"
                      />
                    ),
                  },
                  {
                    min: 8,
                    type: 'string',
                    message: '长度不能小于 8',
                  },
                ]}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <Space split={<Divider type="vertical" />}>
              <Link to="/user/login">已有账号，直接登录</Link>
            </Space>
          </div>
        </LoginForm>
      </div>
      <Footer />
    </div>
  );
};

export default Update;
